package autonomrobot;

import java.awt.Component;
import java.awt.Image;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;

/**
 *
 * @author Ragnar
 */
public class ReadImage implements Runnable
{
    private ImageResource imresource;
    CaptureDeviceInfo device;
    MediaLocator ml;
    Player player;
    Component videoScreen;
    
    public ReadImage(ImageResource imageresource)
    {
        this.imresource = imageresource;
        Thread t = new Thread(this);
        t.start();
    }
    
    @Override
    public void run()
    {
        Image im = this.readImage();
        this.imresource.putImage(im);
    }
    
    public Image readImage()
    {
        try
        {
            ml = new MediaLocator("vfw://0");
            player = Manager.createRealizedPlayer(ml);
            FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
            Buffer b = fgc.grabFrame();
            BufferToImage btoi = new BufferToImage((VideoFormat) b.getFormat());
            Image imaj = btoi.createImage(b);
            return imaj;
        }
        catch (IOException ex)
        {
            Logger.getLogger(ReadImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (NoPlayerException ex)
        {
            Logger.getLogger(ReadImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (CannotRealizeException ex)
        {
            Logger.getLogger(ReadImage.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
